package com.bf.electroplating.util.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.bf.electroplating.service.ControlProblemFindingService;
import com.bf.electroplating.service.PubAttachmentService;
import com.bf.electroplating.util.easyexcel.excel.problem.ProblemFindingExcel;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.alibaba.excel.cache.Ehcache.BATCH_COUNT;

/**
 * 导入数据监听器
 */
@Setter
@Getter
@Slf4j
@Component
public class ProblemFindingExcelListener extends AnalysisEventListener<ProblemFindingExcel> {

    @Autowired
    private ControlProblemFindingService controlProblemFindingService;
    @Autowired
    private PubAttachmentService pubAttachmentService;

    private static final ThreadLocal<MultipartFile> FILE_THREAD_LOCAL = new ThreadLocal<>();

    /**
     * 传过来的图片对象放在这里了
     */
    private Map<String, List<String>> imageMap = new HashMap<>();


    List<ProblemFindingExcel> dataList = new ArrayList<>();

    /**
     * 构造方法
     */
    public ProblemFindingExcelListener() {
    }

    /**
     * 读取excel每行数据
     *
     * @param problemFindingExcel
     * @param analysisContext
     */
    @Override
    public void invoke(ProblemFindingExcel problemFindingExcel, AnalysisContext analysisContext) {
        // 获取当前行号  imageList里面row:4
        int currentRowNum = analysisContext.readSheetHolder().getRowIndex(); // +1 是因为索引从0开始
        problemFindingExcel.setImages(imageMap.get(String.valueOf(currentRowNum)));
        dataList.add(problemFindingExcel);

        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (dataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            dataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println("表头：" + headMap);
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", dataList.size());
        controlProblemFindingService.saveBatch(dataList);
        dataList.clear();
        log.info("存储数据库成功！");
        log.info("{}条数据，清空数据：", dataList.size());
    }

}